package com.pansoft.openplanet.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.UniversalRequestManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.NumberTextWatcher;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.BlockChainFeeSeekBar;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;

import static com.efounder.http.RequestManager.TYPE_GET;

/**
 * 转账 界面
 * Created by yqs on 18-3-23.
 */

public class TransferActivity extends TCBaseActivity implements View.OnClickListener {
    private final static String TAG = "TransferActivity";

    private EditText etToAccoutView;
    private EditText etToAddressView;
    private EditText etCountView;
    private EditText etFromAccountView;
    private EditText etBalanceView;
    private Button butEnter;


//    private TextView tvExpense;
//    private TextView tvMin;
//    private SeekBar seekBar;




    // private List<WalletBean> list;
    private AccountDao accountDao;

    private String myaddress;
    private String balance = "0";
    //转换成千分位的balance
    private String balanceFormatString = "0";
    private String filePath;

    //用户联信号
    private String toAccount;
    //钱包地址
    private String toEthAddressString;
    private String coinNummber;

    private String myNumber;
    //转账金额
    private String count;

    private boolean doSendMsg = false;
    private String toUserId;

    //当前交易的用户
    private User currentTransferUser;
    //矿工费
//    private String gas = "0.0004";

    private BlockChainFeeSeekBar blockFeeSekbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_actiivty_transfer);
        initView();
        initdata();
    }

    private void initdata() {

        if (getIntent().getStringExtra("filePath") != null) {
            filePath = getIntent().getStringExtra("filePath");
            myaddress = getIntent().getStringExtra("myaddress");
            balance = getIntent().getStringExtra("balance");
            balance = balance == null ? "0" : balance;
        } else {
//            getWalletAddress();
//            if (list.get(0).getAddress().toLowerCase().equals(EnvironmentVariable.getProperty("tc_ethAddress").toLowerCase())) {

            Account account = new AccountDao(this).getMainAccount();
            if (account!=null && account.getAddress().toLowerCase().equals(EnvironmentVariable.getProperty("tc_ethAddress").toLowerCase())) {
                //获取本地钱包成功
                //todo 请求余额 4.28取消显示余额
                //getBanlancefromServer();
//                myaddress = list.get(0).getAddress();
//                filePath = list.get(0).getFilePath();
                myaddress = account.getAddress();
                filePath = account.getFileName();
                StubObject stubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
                if (stubObject != null && !stubObject.getString("toUserId", "").equals("")) {
                    doSendMsg = true;
                    toUserId = stubObject.getString("toUserId", "");

                    //todo 转账  手机号换成imuserid 0428
                    toAccount = getNumberFromUserId(Integer.valueOf(toUserId));
                    currentTransferUser = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(toUserId));
                   // toAccount = toUserId;
                    etToAccoutView.setText(toUserId);
                    //etToAccoutView.setText(toAccount);
                    etToAccoutView.setFocusable(false);

                    etToAddressView.setText(currentTransferUser.getWalletAddress());
                    getToAddressFromServer();
                }
                if (getIntent().getStringExtra("toAccount") != null) {
                    toAccount = getIntent().getStringExtra("toAccount");
                    etToAccoutView.setText(toAccount);
                    etToAccoutView.setFocusable(false);
                }
                if (getIntent().getStringExtra("toAddress") != null) {
                    toEthAddressString = getIntent().getStringExtra("toAddress");
                    etToAddressView.setText(toEthAddressString);
                    etToAddressView.setFocusable(false);
                }
                if (getIntent().getStringExtra("count") != null) {
                    count = getIntent().getStringExtra("count");
                    if (count.equals("0") || "".equals(count)) {
                        etCountView.setFocusable(true);
                        etCountView.setText("");
                    } else {
                        etCountView.setText(count);
                        etCountView.setFocusable(false);
                    }

                }

            } else {
                ToastUtils.showShort(ResStringUtil.getString(R.string.wrchatview_get_wallet_fail));
                return;
            }
        }


        myNumber = EnvironmentVariable.getUserName();

        etFromAccountView.setText(myaddress.replace(myaddress.substring(6, myaddress.length() - 4), "****"));
        etBalanceView.setText(balance);
        if (balance == null || "0".equals(balance)) {
            //请求余额
            getBanlancefromServer();
        }

    }

    private void initView() {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_energy_exchange));

        etToAccoutView = (EditText) findViewById(R.id.toAccout);
        etToAddressView = (EditText) findViewById(R.id.toAddress);
        etCountView = (EditText) findViewById(R.id.et_count);
        etCountView.addTextChangedListener(new NumberTextWatcher(etCountView));
        etFromAccountView = (EditText) findViewById(R.id.et_fromCount);
        etBalanceView = (EditText) findViewById(R.id.et_balance);
        butEnter = (Button) findViewById(R.id.but_enter);
        butEnter.setOnClickListener(this);
        blockFeeSekbar = (BlockChainFeeSeekBar) findViewById(R.id.block_fee_sekbar);

//        tvExpense = (TextView) findViewById(R.id.tv_expense);
//        tvMin = (TextView) findViewById(R.id.tv_min);
//        seekBar = (SeekBar) findViewById(R.id.seekBar);
        initSeekBar();
    }

    private void initSeekBar() {
        blockFeeSekbar.setChainId(IPAssetsConstant.CHAIN_ID_TURBOCHAIN);


    }
//    /**
//     * 初始化seekbar，用于计算转账矿工费用
//     * 最小0.0004，最大0.006
//     */
//    private void initSeekBar() {
//        seekBar.setMax(56);
//        //设置滑块颜色
//        seekBar.getThumb().setColorFilter(Color.parseColor("#108ee9"), PorterDuff.Mode.SRC_ATOP);
//        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                gas = BalanceUtil.formatPrice(new BigDecimal((double) (progress + 4) / 10000)
//                                .doubleValue(),
//                        true, 4);
//                tvExpense.setText(gas + " PWR");
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//
//            }
//        });
//    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.but_enter) {
            startTransfer();

        }

    }

    //开始转账
    private void startTransfer() {
        //装转账人帐号（手机号）
        toAccount = etToAccoutView.getText().toString();
        //转账地址
        toEthAddressString = etToAddressView.getText().toString();
        //转账金额
        count = etCountView.getText().toString();


        if (toAccount.trim().isEmpty() || toEthAddressString.trim().isEmpty() || count.trim().isEmpty()) {
            ToastUtils.showShort(R.string.open_planet_input_complete);
            return;
        }
//        if (Double.valueOf(balance.replaceAll("[, ]","")) < Double.valueOf(TCMathUtil.retainAsignDecimalsWithZero(TCMathUtil.add(Double.valueOf(etCountView.getText().toString()),
//                Double.valueOf(gas)),8))) {
         if (new BigDecimal(balance.replaceAll("[, ]","")).compareTo(new BigDecimal(count))<0){

            ToastUtils.showShort(R.string.open_planet_amount_should_not_big_than_balance);

//            ToastUtils.showShort(R.string.open_planet_balance_gas_insufficient);
//            etCountView.setText(TCMathUtil.retainAsignDecimalsWithZero(TCMathUtil.sub(Double.valueOf(balance), Double.valueOf(gas)), 8));
//            etCountView.setSelection(etCountView.getText().toString().length());
            return;
        }
        showPasswordDialog();

    }

    private void showPasswordDialog() {
        PassWordAlertDialog dialog = new PassWordAlertDialog(this, new PassWordAlertDialog.OnEnterClick() {
            @Override
            public void passVerifySuccess(String passWord) {
                Intent intent = new Intent(TransferActivity.this, TransferSuccessActivity.class);
                intent.putExtra("myaddress", myaddress);
                intent.putExtra("balance", balance);
                intent.putExtra("filePath", filePath);
                intent.putExtra("toAccount", toAccount);
                intent.putExtra("toAddress", toEthAddressString);
                intent.putExtra("count", etCountView.getText().toString());
                intent.putExtra("gas",blockFeeSekbar.getProgressGas());
                intent.putExtra("convertGas",blockFeeSekbar.getGasConversion());

                if (doSendMsg) {
                    intent.putExtra("toUserId", toUserId);
                }
                startActivity(intent);
                finish();
            }
        });
        dialog.show();

    }

    //从服务器获取余额
    private void getBanlancefromServer() {
        showLoading(R.string.common_text_please_wait);
        HashMap<String, String> map = new HashMap<>();
        map.put("ethAddress", myaddress);
        TCRequestUtil.postCommonRequest(TAG, "eth/ethGetBalance", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optString("result").equals("success")) {
                        String balance1 = jsonObject.optString("balance");
                        balance1 = BalanceUtil.balanceConvert(balance1);
                        balance = balance1;

                        if (balance1.equals("0")) {
                            balance = balance1;
                        } else {
                            //balance = BalanceUtil.formatPrice(Double.valueOf(balance1), true, 8);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.open_planet_get_balance_fail);
                }
            }

            @Override
            public void onFail(String error) {
                dismissLoading();
                ToastUtils.showShort(R.string.open_planet_get_balance_fail);
            }
        });

    }

    private void getToAddressFromServer() {
        String baseUrl = EnvironmentVariable.getProperty("TalkChainUrl") + "/tcserver/user/getUserByUserId";
        HashMap<String, String> map = new HashMap<>();
        map.put("otherUserId", toAccount);
        UniversalRequestManager.getInstance(this).requestAsyn(baseUrl, TYPE_GET, map, new UniversalRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                // {"result":"success","user":{"ethAddress":"0x66DbaF2d30549aAFed0E468c85da14CBA7E0eA54",
                //   "ethPublicKey":"0x045d1de50d93b86efb04703f4c7b450e91ce501ed704d450073dea931655105fceee5d5e07b203b52c916985ab8bd74c758bd07786f9f747304fe9c788c0c404ad","fromInviteCode":"QU14Q9","imUserId":181540,"inviteCode":"RPY38Y","inviteCodeUseCount":0,"userId":"15898908031","userIdMd5":"D74FC5DA5D3AEB6EF81684ABAB414842","userName":"q"}}
                try {
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                    if (jsonObject.containsKey("result") && jsonObject.getString("result").equals("success")) {
                        net.sf.json.JSONObject jsonObject1 = jsonObject.getJSONObject("user");

                        User currentUser =  WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(toUserId));
                        if (jsonObject1.containsKey("ethAddress")) {
                            currentUser.setWalletAddress(jsonObject1.getString("ethAddress"));
                            toEthAddressString = jsonObject1.getString("ethAddress");
                            etToAddressView.setText(toEthAddressString);
                            etToAddressView.setFocusable(false);
                        }
                        if (jsonObject1.containsKey("ethPublicKey")) {
                            currentUser.setPublicKey(jsonObject1.getString("ethPublicKey"));
                        }

                        WeChatDBManager.getInstance().insertUserTable(currentUser);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onReqFailed(String errorMsg) {

            }
        });
    }

    private String getNumberFromUserId(int userId) {
        User user = WeChatDBManager.getInstance().getOneFriendById(userId);
        return user.getName();
    }

}